package com.yunsuo.bean;

import com.alibaba.fastjson.JSON;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;


public class HttpConnectionCreate {
    public static String connection(){
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            /*拼接url,Android这里需要换上远程地址，因为Android端没办法访问localhost，java的话本地tomcat运行的话倒是无妨*/
            String address = "http://192.168.43.219:8080/lockV1_1_war_exploded/raspberry/createLock";
            URL url = new URL(address);
            HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
            //这两个参数必须加
            httpURLConnection.setDoInput(true);
            httpURLConnection.setDoOutput(true);
            //设置超时时间
            httpURLConnection.setReadTimeout(10*1000);
            httpURLConnection.setConnectTimeout(10*1000);
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.connect();

            final String user = "info=createLock";
            out = new PrintWriter(httpURLConnection.getOutputStream());
            //在输出流中写入参数
            out.print(user);
            out.flush();

            if(httpURLConnection.getResponseCode() == 200){
                in = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream(),"utf-8"));
                String line;
                while((line=in.readLine())!=null){
                    result+=line;
                }
            }
            //System.out.println("服务器返回的结果是："+result);
            return result;
        } catch (
                MalformedURLException e) {
            //System.out.println("URL异常");
            e.printStackTrace();
        } catch (
                IOException e) {
            //System.out.println("IO异常");
            e.printStackTrace();
        } finally {
            try{
                if(out!=null)
                    out.close();
                if(in!=null)
                    in.close();
            }catch (IOException e) {
                e.printStackTrace();
            }
        }
        //得到服务器返回的数据，[{"pId":1,"pUId":1,"pAccountNum":"1","pPassword":"1","pDelete":0,"pModify":0}]
        return result;
    }

}
